package com.example.blockbreaker;

import com.example.blockbreaker.R;
import com.google.android.material.snackbar.Snackbar;

import android.animation.ValueAnimator;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class BreathingActivity extends AppCompatActivity {
    private ImageView circleImage;
    private TextView instructionText;
    private ValueAnimator animator;

    private Button btnFinish;
    private long startTime;
    private SharedPreferences prefs;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_breathing);

        circleImage = findViewById(R.id.breathing_circle);
        instructionText = findViewById(R.id.breathing_instruction);

        // 初始化组件
        btnFinish = findViewById(R.id.btn_finish);
        prefs = getSharedPreferences("QuitSmokePrefs", MODE_PRIVATE);
        startTime = System.currentTimeMillis();

        startBreathingAnimation();
        // 设置完成按钮点击事件
        setupFinishButton();
    }

    private void setupFinishButton() {
        btnFinish.setOnClickListener(v -> {
            // 1. 停止呼吸动画
            stopBreathingAnimation();

            // 2. 记录练习完成情况
            recordBreathingExercise();

            // 3. 显示鼓励消息
            showCompletionMessage();

            // 4. 关闭活动
            finish();
        });
    }

    private void showCompletionMessage() {
        // 获取统计数据
        long durationSeconds = (System.currentTimeMillis() - startTime) / 1000;
        int totalSessions = prefs.getInt("breathing_sessions", 0);
        long averageDuration = prefs.getLong("breathing_avg_duration", 0);

        // 创建鼓励消息
        String message;
        if (durationSeconds > 180) { // 超过3分钟
            message = "太棒了！你坚持了" + durationSeconds + "秒深呼吸练习\n继续保持！";
        } else if (totalSessions > 5) {
            message = "做得不错！这是你的第" + totalSessions + "次练习\n平均时长" + averageDuration + "秒";
        } else {
            message = "完成" + durationSeconds + "秒深呼吸练习\n烟瘾会逐渐减弱的，加油！";
        }

        // 显示Toast消息
        Toast.makeText(this, message, Toast.LENGTH_LONG).show();

        // 或者使用更美观的Snackbar
        View rootView = findViewById(android.R.id.content);
        Snackbar.make(rootView, message, Snackbar.LENGTH_LONG)
                .setAction("确定", v -> { /* 可选操作 */ })
                .show();
    }
    private void recordBreathingExercise() {
        // 计算练习持续时间(秒)
        long durationSeconds = (System.currentTimeMillis() - startTime) / 1000;

        // 获取SharedPreferences编辑器
        SharedPreferences.Editor editor = prefs.edit();

        // 更新呼吸练习统计数据
        int totalSessions = prefs.getInt("breathing_sessions", 0) + 1;
        long totalDuration = prefs.getLong("breathing_total_duration", 0) + durationSeconds;

        editor.putInt("breathing_sessions", totalSessions);
        editor.putLong("breathing_total_duration", totalDuration);
        editor.putLong("last_breathing_time", System.currentTimeMillis());

        // 保存本次练习持续时间
        editor.putLong("last_breathing_duration", durationSeconds);

        // 计算平均持续时间
        long averageDuration = totalDuration / totalSessions;
        editor.putLong("breathing_avg_duration", averageDuration);

        editor.apply();

        // 可以在日志中查看记录结果
        Log.d("BreathingExercise", String.format(
                "呼吸练习完成: 本次%d秒, 平均%d秒, 总计%d次",
                durationSeconds, averageDuration, totalSessions));
    }
    private void stopBreathingAnimation() {
        if (animator != null && animator.isRunning()) {
            animator.cancel();
        }
    }
    private void startBreathingAnimation() {
        animator = ValueAnimator.ofFloat(0.5f, 1.5f);
        animator.setDuration(4000); // 4秒吸气
        animator.setRepeatCount(ValueAnimator.INFINITE);
        animator.setRepeatMode(ValueAnimator.REVERSE);

        animator.addUpdateListener(animation -> {
            float scale = (float) animation.getAnimatedValue();
            circleImage.setScaleX(scale);
            circleImage.setScaleY(scale);

            if (scale < 1.0f) {
                instructionText.setText("呼气...");
            } else {
                instructionText.setText("吸气...");
            }
        });

        animator.start();
    }

    @Override
    protected void onDestroy() {
        if (animator != null) {
            animator.cancel();
        }
        super.onDestroy();
    }
}